<?php

namespace app\admin\controller;


use think\Cache;

class Banner extends BaseController {
    public function _initialize() {
        $bannerTimeLine = Cache::get('bannerTimeLine');
        if ($bannerTimeLine) {
            return;
        }
        $banners = model('Banner')
            ->where('status', 'neq', config('code.status_delete'))
            ->field('id,expert,status')
            ->select();
        $now     = time();
        foreach ($banners as $banner) {
            $expert = $banner->expert;
            if ($now > $expert && $banner->status != 2) {
                $banner->status = 2;
                $banner->save();
            }
        }
        Cache::set('bannerTimeLine', '2个小时', config('setting.token_expire_in'));
    }

    public function index() {
        $query = input('get.');
        validate('Banner')->goCheck('admin');
        $condition = [];
        if (!empty($query['position_id'])) {
            $condition['position_id'] = $query['position_id'];
        }
        if (!empty($query['status'] && $query['status'] != 3) || $query['status'] == 0) {
            $condition['status'] = $query['status'];
        }
        $this->getPageAndSize($query);
        $result = model('Banner')->getBannerList($condition, $this->from, $this->size);
        return show(0, '获取数据成功', $result);
    }

    public function read($id) {
        $query = input('get.');
        if (!empty($query['type']) && $query['type'] === 'category') {
            $result = model('Category')->getCategoryByInfoId($id);
            return show(config('code.success'), '获取所属分类成功', $result);
        }
    }

    public function save() {
        $data           = input('post.');
        $data['expert'] = $data['expert'] + time();
        if (empty($data['id'])) {
            $result = model('Banner')->add($data);
        } else {
            $result = model('Banner')->edit($data, $data['id']);
        }
        if (!$result) {
            return show(config('code.fail'), '保存失败');
        }
        return show(config('code.success'), '保存成功');
    }

    public function update($id) {
        $query  = input('get.');
        $result = model('Banner')
            ->where(['id' => $id])
            ->update(['status' => $query['status']]);
        if (!$result) {
            return show(1, '修改失败');
        }
        return show(0, '修改成功');
    }

    public function delete($id) {
        $result = model('Banner')->where(['id' => $id])->update(['status' => config('code.status_delete')]);
        if (!$result) {
            return show(1, '删除失败');
        }
        return show(0, '删除成功');
    }
}